<template>
    <div class="login-modal" v-if="visible" @click.self="handleClose">
        <div class="modal-content">
            <!-- 左侧图片区域 -->
            <div class="modal-left">
                <img :src="modalLeftImg" alt="登录页面装饰图">
            </div>
            
            <!-- 右侧登录区域 -->
            <div class="modal-right">
                <div class="close-btn" @click="handleClose">
                    <svg-icon name="close" />
                </div>
                
                <div class="login-header">
                    <h2>欢迎登录</h2>
                    <p>登录后体验更多功能</p>
                </div>

                <form class="login-form" @submit.prevent="handleSubmit">
                    <!-- 账号输入框 -->
                    <div class="form-item">
                        <svg-icon name="user" class="input-icon" />
                        <input
                            type="text"
                            v-model="formData.username"
                            placeholder="请输入账号"
                            :class="{ 'error': errors.username }"
                        >
                        <span class="error-message" v-if="errors.username">{{ errors.username }}</span>
                    </div>

                    <!-- 密码输入框 -->
                    <div class="form-item">
                        <svg-icon name="lock" class="input-icon" />
                        <input
                            :type="showPassword ? 'text' : 'password'"
                            v-model="formData.password"
                            placeholder="请输入密码"
                            :class="{ 'error': errors.password }"
                        >
                        <svg-icon
                            :name="showPassword ? 'eye-open' : 'eye-close'"
                            class="toggle-password"
                            @click="showPassword = !showPassword"
                        />
                        <span class="error-message" v-if="errors.password">{{ errors.password }}</span>
                    </div>

                    <!-- 验证码 -->
                    <div class="form-item captcha-wrapper">
                        <div class="captcha-input">
                            <svg-icon name="verify" class="input-icon" />
                            <input
                                type="text"
                                v-model.trim="formData.captcha"
                                placeholder="请输入验证码"
                                :class="{ 'error': errors.captcha }"
                                @focus="handleCaptchaFocus"
                            >
                        </div>
                        <img
                            v-if="captchaImg"
                            :src="'data:image/png;base64,' + captchaImg"
                            alt="验证码"
                            class="captcha-image"
                            @click="refreshCaptcha"
                        >
                        <transition name="fade">
                            <div class="error-message" v-if="errors.captcha">
                                <svg-icon name="error" class="error-icon" />
                                <span>{{ errors.captcha }}</span>
                            </div>
                        </transition>
                    </div>

                    <button type="submit" class="submit-btn" :disabled="loading" @click.prevent="handleSubmit">
                        {{ loading ? '登录中...' : '登录' }}
                    </button>

                    <div class="form-footer">
                        <a href="#" class="forgot-password">忘记密码？</a>
                        <a href="#" class="register-link" @click.prevent="showRegister">注册账号</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useLoginStore } from '@/stores/login'
import { getCaptcha } from '@/api/user'
import modalLeftImg from '@/assets/images/modal-left.jpeg'

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['update:visible'])

const router = useRouter()
const userStore = useUserStore()
const loginStore = useLoginStore()

const showPassword = ref(false)
const loading = ref(false)
const captchaImg = ref('')  // 验证码图片URL

const formData = reactive({
    username: '',
    password: '',
    captcha: '',
    uuid: ''
})

const errors = reactive({
    username: '',
    password: '',
    captcha: ''
})

// 监听visible变化，当显示时刷新验证码
watch(() => props.visible, (newVal) => {
    if (newVal) {
        refreshCaptcha()
    }
})

// 刷新验证码
const refreshCaptcha = async () => {
    try {
        const res = await getCaptcha()
        if (res.code === 200) {
            const { img, uuid } = res.data
            captchaImg.value = img
            formData.uuid = uuid
            formData.captcha = ''
            errors.captcha = ''
        }
    } catch (error) {
        errors.captcha = error.message || '获取验证码失败，请点击刷新'
    }
}

// 组件挂载时获取验证码
onMounted(() => {
    refreshCaptcha()
})

// 表单验证
const validateForm = () => {
    let isValid = true
    errors.username = ''
    errors.password = ''
    errors.captcha = ''

    if (!formData.username) {
        errors.username = '请输入用户名'
        isValid = false
    } else if (formData.username.length < 2) {
        errors.username = '用户名长度不能小于2位'
        isValid = false
    }

    if (!formData.password) {
        errors.password = '请输入密码'
        isValid = false
    } else if (formData.password.length < 6) {
        errors.password = '密码长度不能小于6位'
        isValid = false
    }

    if (!formData.captcha) {
        errors.captcha = '请输入验证码'
        isValid = false
    } else if (formData.captcha.length < 4) {
        errors.captcha = '验证码长度不正确'
        isValid = false
    }

    return isValid
}

// 提交表单
const handleSubmit = async () => {
    if (!validateForm()) return

    try {
        loading.value = true
        const loginRes = await userStore.login({
            username: formData.username,
            password: formData.password,
            code: formData.captcha,
            uuid: formData.uuid
        })

        if (loginRes && loginRes.token) {
            emit('update:visible', false)
        }
    } catch (error) {
        if (error.message) {
            const errorMsg = error.message
            if (errorMsg.includes('验证码')) {
                errors.captcha = errorMsg
                formData.captcha = ''
            } else if (errorMsg.includes('密码')) {
                errors.password = errorMsg
            } else if (errorMsg.includes('用户')) {
                errors.username = errorMsg
            }
        }
    } finally {
        loading.value = false
    }
}

// 添加输入框聚焦事件处理
const handleCaptchaFocus = () => {
    if (errors.captcha) {
        errors.captcha = ''
        refreshCaptcha()  // 只在用户主动聚焦时刷新验证码
    }
}

// 显示注册弹窗
const showRegister = () => {
    emit('update:visible', false)
    loginStore.showRegister()
}

// 关闭弹窗
const handleClose = () => {
    emit('update:visible', false)
}
</script>

<style lang="scss" scoped>
@use "sass:color";

.login-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .modal-content {
        display: flex;
        background: #fff;
        border-radius: 8px;
        overflow: hidden;
        width: 800px;
        max-width: 90%;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

        .modal-left {
            width: 400px;
            flex-shrink: 0;
            
            img {
                width: 400px;
                height: 600px;
                object-fit: cover;
            }
        }

        .modal-right {
            position: relative;
            width: 400px;
            flex-shrink: 0;
            padding: 40px;
            box-sizing: border-box;

            .login-form {
                max-width: 320px;
                margin: 0 auto;
                width: 100%;
                
                .form-item {
                    position: relative;
                    margin-bottom: 24px;
                    width: 100%;

                    .input-icon {
                        position: absolute;
                        left: 12px;
                        top: 50%;
                        transform: translateY(-50%);
                        width: 20px;
                        height: 20px;
                        color: #999;
                        pointer-events: none;
                    }

                    input {
                        width: 100%;
                        height: 44px;
                        padding: 0 12px 0 40px;
                        border: 1px solid #ddd;
                        border-radius: 4px;
                        font-size: 14px;
                        color: #333;
                        box-sizing: border-box;
                        transition: all 0.3s;

                        &::placeholder {
                            color: #999;
                            font-size: 14px;
                        }

                        &:focus {
                            border-color: #4A60A1;
                            box-shadow: 0 0 0 2px rgba(74, 96, 161, 0.1);
                            outline: none;
                        }

                        &.error {
                            border-color: #ff4d4f;
                            background-color: #fff2f0;
                        }
                    }

                    .toggle-password {
                        position: absolute;
                        right: 12px;
                        top: 50%;
                        transform: translateY(-50%);
                        width: 20px;
                        height: 20px;
                        color: #999;
                        cursor: pointer;
                        transition: color 0.3s;

                        &:hover {
                            color: #333;
                        }
                    }

                    .error-message {
                        position: absolute;
                        left: 0;
                        bottom: -20px;
                        display: flex;
                        align-items: center;
                        gap: 4px;
                        font-size: 12px;
                        color: #ff4d4f;
                        line-height: 1.5;
                        
                        .error-icon {
                            width: 14px;
                            height: 14px;
                            color: #ff4d4f;
                        }
                    }
                }

                .captcha-wrapper {
                    display: flex;
                    gap: 12px;
                    width: 100%;

                    .captcha-input {
                        position: relative;
                        flex: 1;
                        min-width: 0;
                        width: calc(100% - 132px);
                    }

                    .captcha-image {
                        height: 44px;
                        width: 120px;
                        border-radius: 4px;
                        cursor: pointer;
                        border: 1px solid #ddd;
                        flex-shrink: 0;
                    }
                }

                .submit-btn {
                    width: 100%;
                    height: 44px;
                    background: #4A60A1;
                    border: none;
                    border-radius: 4px;
                    color: #fff;
                    font-size: 16px;
                    cursor: pointer;
                    transition: background 0.3s;

                    &:hover {
                        background: color.adjust(#4A60A1, $lightness: -5%);
                    }

                    &:disabled {
                        background: #ccc;
                        cursor: not-allowed;
                    }
                }

                .form-footer {
                    width: 100%;
                    margin-top: 16px;
                    display: flex;
                    justify-content: space-between;
                    font-size: 14px;

                    a {
                        color: #666;
                        text-decoration: none;
                        transition: color 0.3s;

                        &:hover {
                            color: #4A60A1;
                        }
                    }
                }
            }
        }
    }
}

// 添加响应式布局
@media screen and (max-width: 768px) {
    .login-modal .modal-content {
        flex-direction: column;
        width: 100%;
        max-width: 400px;
        margin: 20px;
        
        .modal-left {
            display: none;
        }
        
        .modal-right {
            width: 100%;
            padding: 30px 20px;
        }
    }
}

.close-btn {
    position: absolute;
    top: 16px;
    right: 16px;
    cursor: pointer;
    padding: 8px;
    
    .svg-icon {
        width: 20px;
        height: 20px;
        color: #999;
        transition: color 0.3s;
    }

    &:hover .svg-icon {
        color: #333;
    }
}

.login-header {
    text-align: center;
    margin-bottom: 40px;

    h2 {
        font-size: 24px;
        color: #333;
        margin-bottom: 8px;
    }

    p {
        font-size: 14px;
        color: #999;
    }
}

.submit-btn {
    width: 100%;
    height: 44px;
    background: #4A60A1;
    border: none;
    border-radius: 4px;
    color: #fff;
    font-size: 16px;
    cursor: pointer;
    transition: background 0.3s;

    &:hover {
        background: color.adjust(#4A60A1, $lightness: -5%);
    }

    &:disabled {
        background: #ccc;
        cursor: not-allowed;
    }
}

.form-footer {
    margin-top: 16px;
    display: flex;
    justify-content: space-between;
    font-size: 14px;

    a {
        color: #666;
        text-decoration: none;
        transition: color 0.3s;

        &:hover {
            color: #4A60A1;
        }
    }
}

// 添加错误信息过渡动画
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style> 